// util/nightingale_v8_client.go
package util

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"

	"v2/config"
)

// NightingaleV8Client 夜莺V8客户端
type NightingaleV8Client struct {
	BaseURL  string
	Username string
	Password string
}

// NewNightingaleV8Client 创建夜莺V8客户端
func NewNightingaleV8Client() *NightingaleV8Client {
	return &NightingaleV8Client{
		BaseURL:  config.Global.Nightingale.URL,
		Username: config.Global.Nightingale.Username,
		Password: config.Global.Nightingale.Password,
	}
}

// MuteRule 屏蔽规则（符合夜莺V8 API）
type MuteRule struct {
	GroupID       int            `json:"group_id"`
	Note          string         `json:"note"`
	Severities    []int          `json:"severities"`
	DatasourceIDs []int          `json:"datasource_ids"`
	BTime         int            `json:"btime"`
	ETime         int            `json:"etime"`
	Tags          []TagCondition `json:"tags"`
	Cause         string         `json:"cause"`
	MuteTimeType  int            `json:"mute_time_type"`
	PeriodicMutes []PeriodicMute `json:"periodic_mutes"`
}

// TagCondition 标签条件
type TagCondition struct {
	Func  string `json:"func"`
	Key   string `json:"key"`
	Value string `json:"value"`
}

// PeriodicMute 周期性屏蔽
type PeriodicMute struct {
	EnableSTime      string `json:"enable_stime"`
	EnableETime      string `json:"enable_etime"`
	EnableDaysOfWeek string `json:"enable_days_of_week"`
}

// MuteResponse 屏蔽响应
// MuteResponse 屏蔽响应
type MuteResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		ID int `json:"id"`
	} `json:"data"`
}

// MuteAlert 屏蔽告警
// MuteAlert 屏蔽告警
func (c *NightingaleV8Client) MuteAlert(muteRule MuteRule) (*MuteResponse, error) {
	if !config.Global.Nightingale.Enable {
		log.Printf("[Nightingale] 夜莺功能已禁用")
		return &MuteResponse{
			Code:    200,
			Message: "夜莺功能已禁用（测试模式）",
			Data: struct {
				ID int `json:"id"`
			}{
				ID: 1,
			},
		}, nil
	}

	// 构建请求URL
	url := fmt.Sprintf("%s/v1/n9e/alert-mutes", c.BaseURL)

	// 构建请求体
	reqBody, err := json.Marshal(muteRule)
	if err != nil {
		return nil, fmt.Errorf("序列化屏蔽规则失败: %v", err)
	}

	log.Printf("[Nightingale] 请求夜莺API: %s, 数据: %s", url, string(reqBody))

	// 创建请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置Basic认证头
	if c.Username != "" && c.Password != "" {
		auth := c.Username + ":" + c.Password
		encodedAuth := base64.StdEncoding.EncodeToString([]byte(auth))
		req.Header.Set("Authorization", "Basic "+encodedAuth)
	} else {
		log.Printf("[Nightingale] 警告: 未配置用户名和密码，可能认证失败")
	}

	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("请求夜莺API失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}

	log.Printf("[Nightingale] 夜莺API响应状态码: %d", resp.StatusCode)
	log.Printf("[Nightingale] 夜莺API原始响应: %s", string(body))

	// 检查状态码
	if resp.StatusCode != http.StatusOK {
		// 尝试解析可能的错误信息
		var errorResp struct {
			Code    int    `json:"code"`
			Message string `json:"message"`
		}

		if json.Unmarshal(body, &errorResp) == nil {
			return nil, fmt.Errorf("夜莺API返回错误: %d, %s", errorResp.Code, errorResp.Message)
		}

		// 如果无法解析，返回原始响应
		return nil, fmt.Errorf("夜莺API返回非200状态码: %d, 响应: %s", resp.StatusCode, string(body))
	}

	// 处理响应
	var muteResp MuteResponse
	if err := json.Unmarshal(body, &muteResp); err != nil {
		return nil, fmt.Errorf("解析响应失败: %v, 原始响应: %s", err, string(body))
	}

	if muteResp.Code != 0 {
		return nil, fmt.Errorf("夜莺API返回错误: %d, %s", muteResp.Code, muteResp.Message)
	}

	return &muteResp, nil
}
